/**
 * Actively Replicated Crash Free Single Software Failure (non Byzantine)
 * Distributed Retail Store 
 * 
 * Nov. 24 2012
 */
package comp6231.project.frontend;

import comp6231.project.common.Message;

/**
 * Retail store front end CORBA object that is responsible for receiving
 * client requests for store operations (buy, return, exchange, check stock)
 * and forwarding requests to Sequencer for total ordering of requests and to
 * Replica Manager for request processing and error detection. 
 * 
 * @author dimitri.tiago
 */
public class RetailStoreFrontEnd extends RetailStoreFrontEndInterfacePOA {

	private Sequencer sequencer;			
	private ReplicaManager replicaManager;	
	
	/**
	 * Default constructor initializes instance variables
	 */
	public RetailStoreFrontEnd(ReplicaManager rm)
	{
		sequencer 		= new Sequencer();
		replicaManager 	= rm;
	}
	
	@Override
	public int buyItems (String customerID, int itemID, int numberOfItem) {

		// create request message
		Message request 	= new Message();
		request.request		= request.REQUEST_BUY;
		request.customerID 	= customerID;
		request.itemID 		= String.format("%04d", itemID);
		request.numItems	= numberOfItem;
		
		// set request message total order
		sequencer.setTotalOrder(request);
		return replicaManager.processMessageFromSequencer(request);
	}

	@Override
	public int returnItems (String customerID, int itemID, int numberOfItem) {
		
		// create request message
		Message request 	= new Message();
		request.request		= request.REQUEST_RETURN;
		request.customerID 	= customerID;
		request.itemID 		= String.format("%04d", itemID);;
		request.numItems	= numberOfItem;
		
		// set request message total order
		sequencer.setTotalOrder(request);
		return replicaManager.processMessageFromSequencer(request);
	}

	@Override
	public int checkStock (int itemID) {
		
		// create request message
		Message request 	= new Message();
		request.request		= request.REQUEST_CHECKSTOCK;
		request.itemID 		= String.format("%04d", itemID);;
		
		// set request message total order
		sequencer.setTotalOrder(request);
		return replicaManager.processMessageFromSequencer(request);
	}

	@Override
	public int exchangeItems (
			String customerID, 
			int boughtItemID, 
			int boughtNumber, 
			int desiredItemID, 
			int desiredNumber) {

		// create request message
		Message request 		 = new Message();
		request.request			 = request.REQUEST_EXCHANGE;
		request.customerID 		 = customerID;
		request.itemID 			 = String.format("%04d", boughtItemID);
		request.numItems		 = boughtNumber;
		request.exchangeItemID 	 = String.format("%04d", desiredItemID);
		request.numExchangeItems = desiredNumber;
		
		// set request message total order
		sequencer.setTotalOrder(request);
		return replicaManager.processMessageFromSequencer(request);
	}
}